<template>
  <div>
    <Title title="基础信息" style="margin-bottom: 24px;" />
    <el-form
      ref="formRef"
      :model="paramsObj"
      :rules="formRules"
      :label-width="labelWidth"
      :label-position="formAlign"
      class="lineHeight32">
      <el-row type="flex" class="response-el-row">
        <el-col :span="rowSpan">
          <el-form-item label="供应商类型" prop="supplierType">
            <selectWithoutHttp v-model="paramsObj.supplierType" :list-data="supplierTypeOptions" class="width240" key-name="id" label-name="label" @change="supplierTypeChange"/>
          </el-form-item>
        </el-col>
        <el-col :span="rowSpan">
          <el-form-item label="供应商名称" prop="channelName">
            <el-autocomplete
              v-if="!isCreateSupplier"
              v-model.trim="paramsObj.channelName"
              :fetch-suggestions="querySearch"
              :maxlength="50"
              class="width240"
              size="small"
              placeholder="输入供应商名称"
              @change="channelNameChange"
              @select="handleSelect"
            />
            <el-input v-else :disabled="canEdit" v-model.trim="paramsObj.channelName" :maxlength="50" class="width240" placeholder="输入供应商名称" type="text" size="small" />
          </el-form-item>
        </el-col>
        <el-col :span="rowSpan">
          <el-form-item label="所属部门" prop="departmentId">
            <el-cascader
              v-model="paramsObj.departmentId"
              :show-all-levels="false"
              :options="deptTreeList"
              :props="{
                emitPath:false,
                value: 'id',
                label: 'name',
                checkStrictly: true,
                multiple: false,
              }"
              class="width240"
              placeholder="请选择所属部门"
              size="small"
              collapse-tags
              clearable
              filterable
            >
              <template slot-scope="{ data }">
                <el-tooltip v-if="data.name.length > 14" placement="top-start" effect="dark">
                  <div slot="content" style="max-width: 150px;">{{ data.name }}</div>
                  <span class="inline-tag ellipsisOne">{{ data.name }}</span>
                </el-tooltip>
                <span v-else>{{ data.name }}</span>
              </template>
            </el-cascader>
          </el-form-item>
        </el-col>
        <el-col v-if="isCreateSupplier" :span="rowSpan">
          <el-form-item label="是否签约" prop="isSignUp">
            <el-radio-group v-model="paramsObj.isSignUp" @change="changeValue">
              <el-radio :label="true"><span style="font-size:14px;">是</span></el-radio>
              <el-radio :label="false"><span style="font-size:14px;">否</span></el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="rowSpan">
          <el-form-item label="可抵扣税率" prop="taxRate">
            <el-input
              v-model="paramsObj.taxRate"
              name="taxRate"
              class="width240"
              size="small"
              @input="deductionRateInput"
            >
              <span slot="suffix" style="margin-right:5px;color:#333;">%</span>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col v-if="isCreateSupplier" :span="rowSpan" class="responsive-col-lg-8">
          <el-form-item label="标签" prop="tag">
            <TagSelect v-model="paramsObj.tag" :module-type="moduleType" class="width240" />
          </el-form-item>
        </el-col>
      </el-row>

    </el-form>
  </div>
</template>

<script>
/**
 *签约审批和销售供应商共用
 */
// components
import Title from '@/components/Title';
import selectWithoutHttp from '@/components/Common/selectWithoutHttp';
import ThreeLevelArea from '@/components/ThreeLevelArea';
import upAttachment from '@/components/Common/upAttachment/index';
import TagSelect from '@/components/Common/tagSelect';
// api
import { getDeptInfo } from '@/api/resource';
import { supplierManageList } from '@/api/supplier';
import { getDepartmentAll } from '@/api/config';
// tool
import { mapState } from 'vuex';
import { percentRate } from '@/utils/numFormat';
import { TAG_MODULES } from '@/utils/const';
import { hasRouteAuth } from '@/utils/permission';
import { supplierSource } from '@/filters/status';
import mobileCreate from '@/mixins/mobileCreate';

export default {
  components: { Title, selectWithoutHttp, ThreeLevelArea, upAttachment, TagSelect },
  mixins: [mobileCreate],
  model: {
    prop: 'paramsObj',
    event: 'changeValue'
  },
  props: {
    paramsObj: {
      type: Object,
      default: () => {
        return {};
      }
    },
    labelWidth: {
      type: String,
      default: '100px'
    },
    isCreateSupplier: {
      type: Boolean,
      default: false
    },
    moduleType: {
      type: Number,
      default: TAG_MODULES.SETTLE_SUPPLIER
    },
    isEdit: {
      type: Boolean,
      default: false
    },
    rowSpan: {
      type: Number,
      default: 12
    }
  },
  data() {
    const validateName = (msg) => {
      return (rule, value, callback) => {
        const name = this.paramsObj.isSignUp;
        if (!name && name !== false) { callback(new Error(msg)); } else { callback(); }
      };
    };
    return {
      TAG_MODULES,
      formRules: {
        supplierType: [{ required: true, trigger: 'change', message: '请选择供应商类型' }],
        channelName: [{ required: true, trigger: 'change', message: '请输入供应商名称' }],
        departmentId: [{ required: true, trigger: 'change', message: '请选择所属部门' }],
        isSignUp: [{ required: true, trigger: 'change', validator: validateName('请选择是否签约') }]
      },
      deptTreeList: [],
      attributionMatrixList: [],
      supplierTypeOptions: [{ id: 0, label: '个人' }, { id: 1, label: '公司' }],
      articlesStatusOptions: [{ id: 0, label: '正常上刊' }, { id: 1, label: '解约下刊' }, { id: 2, label: '处罚停刊' }],
      cooperationStatusOptions: [{ id: 0, label: '正常合作' }, { id: 1, label: '终止合作' }]
    };
  },
  computed: {
    source() {
      return this.supplierSource(this.paramsObj.source);
    },
    ...mapState({
      'userInfo': state => state.user.userInfo
    }),
    canEdit() {
      return !!(this.isCreateSupplier && !this.hasRouteAuth('medium:supplier:editSupplierName') && this.isEdit);
    }
  },
  created() {
    this.queryDeptTreeList();
    this.paramsObj.createUser = this.userInfo.userName;
    const departmentAry = this.userInfo.departmentAry;
    if (departmentAry && departmentAry.id && departmentAry.id.length > 0) {
      this.paramsObj.departmentId = departmentAry.id[0][ departmentAry[0].length - 1];
    } else if (this.userInfo.subDepartment && this.userInfo.subDepartment.length > 0 && this.userInfo.subDepartment[0].id) {
      this.paramsObj.departmentId = this.userInfo.subDepartment[0].id;
    } else if (this.userInfo.deptName && this.userInfo.deptName.length > 0 && this.userInfo.deptName[0].id) {
      this.paramsObj.departmentId = this.userInfo.deptName[0].id;
    }
    this.$emit('changeValue', this.paramsObj);
  },
  methods: {
    hasRouteAuth,
    supplierSource,
    deductionRateInput(value) {
      const str = percentRate(value);
      this.paramsObj.taxRate = str;
      this.$emit('changeValue', this.paramsObj);
    },
    // 选择城市
    threeLevelArea(data) {
      this.paramsObj.region = data.join(',');
      this.$emit('changeValue', this.paramsObj);
    },
    changeValue() {
      this.$emit('changeValue', this.paramsObj);
    },
    handelArr(data) {
      if (!data) return [];
      if (typeof data === 'string') {
        return data.split(',');
      } else {
        return data;
      }
    },
    // 上传文件
    upProgress() {
      // this.createLoading = true;
    },
    complateSetData({ data, fileName }, key) {
      const fileList = {
        name: fileName,
        url: data.url,
        time: new Date().getTime()
      };
      if (typeof data === 'string') {
        fileList.url = data;
      } else {
        fileList.url = data.url;
      }
      if (this.paramsObj[key]) {
        this.paramsObj[key].push(fileList);
      } else {
        this.$set(this.paramsObj, key, [fileList]);
      }
      this.$emit('changeValue', this.paramsObj);
    },
    removeFileList({ file, index }, key) {
      this.paramsObj[key].splice(index, 1);
    },
    validateForm(validate = true) {
      return new Promise((resolve, reject) => {
        if (validate) {
          this.$refs.formRef.validate(valid => {
            if (valid) {
              resolve(valid);
            } else {
              reject(false);
            }
          });
        } else {
          resolve(true);
        }
      });
    },
    channelNameChange() {
      this.$set(this.paramsObj, 'supplierId', '');
    },
    querySearch(queryString, cb) {
      if (!queryString || queryString.length > 30) {
        cb([]);
        return;
      }
      const params = {
        page: 1,
        perPage: 0,
        supplier: queryString,
        notShowNoAuthTip: true
      };
      supplierManageList(params).then(res => {
        if (res.data && res.data.items) {
          res.data.items.forEach(i => {
            i.value = i.supplier;
          });
          cb(res.data.items);
        } else {
          cb([]);
        }
      }).catch(() => {
        cb([]);
      });
    },
    handleSelect(item) {
      this.paramsObj.supplierId = item.supplierCode;
      this.$emit('setSupplierId', Number(item.id));
    },
    supplierTypeChange() {
      this.$nextTick(() => {
        this.$refs.formRef.clearValidate();
      });
    },
    // 获取所属部门
    queryDeptTreeList() {
      getDepartmentAll().then(res => {
        this.deptTreeList = (res && res.data) || [];
      });
    },
    loadDeptInfo() {
      // 获取所属部门
      getDeptInfo().then(res => {
        this.attributionMatrixList = res.data;
      });
    },
    jsonParse(arr) {
      if (!arr) return [];
      try {
        return JSON.parse(arr);
      } catch (error) {
        return [];
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.width240 {
  width: 240px;
  &::v-deep {
    .el-select {
      width: 240px;
    }
    .el-input__inner {
      width: 240px;
    }
  }
}
.mock-input {
  width: 240px;
  background-color: #F5F7FA;
  border:1px solid #E4E7ED;
  border-radius: 4px;
  height: 32px;
  line-height: 32px;
  color: #C0C4CC;
  cursor: not-allowed;
  padding: 0 8px;
}
.height32 {
  &::v-deep {
    .el-cascader {
      line-height: 32px;
    }
  }
}
</style>
